package com.juyu.miliao.api.service;

import com.alibaba.fastjson.JSONObject;
import com.juyu.miliao.api.constant.EnergyLevelType;
import com.juyu.miliao.api.dao.elasticsearch.FindDynamicCommentElasticsearch;
import com.juyu.miliao.api.dao.elasticsearch.FindDynamicElasticsearch;
import com.juyu.miliao.api.dao.mysql.FindDynamicCommentDao;
import com.juyu.miliao.api.dao.redis.DynamicCommentInfoRedisDao;
import com.juyu.miliao.api.dao.redis.usercache.UserCacheVo;
import com.juyu.miliao.api.dao.redis.usercache.UserInfoCache;
import com.juyu.miliao.api.domain.FindDynamicCommentInfo;
import com.juyu.miliao.api.domain.dto.FindDynamicCommentDTO;
import com.juyu.miliao.api.domain.vo.*;
import com.juyu.miliao.api.handler.IntegralRewardsAndPunishmentsHandler;
import com.juyu.miliao.api.util.SystemMessageUtil;
import com.juyu.miliao.common.constant.SpendSystemMessage;
import com.juyu.miliao.common.constant.SpendSystemMessageType;
import com.juyu.miliao.common.exception.ConsumeRuntimeException;
import com.juyu.miliao.common.netease.NetEaseCloudUserService;
import com.juyu.miliao.common.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xuanqicheng
 */
@Service
public class FindDynamicCommentService {

    private static final Logger logger = LoggerFactory.getLogger("dynamicCommentLog");

    @Autowired
    private FindDynamicElasticsearch findDynamicElasticsearch;

    @Autowired
    private FindDynamicCommentDao findDynamicCommentDao;

    @Autowired
    private FindDynamicCommentElasticsearch findDynamicCommentElasticsearch;

    @Autowired
    private FindCommentReplyInfoService findCommentReplyInfoService;

    @Autowired
    private UserInfoCache userInfoCache;

    @Autowired
    private IntegralRewardsAndPunishmentsHandler integralRewardsAndPunishmentsHandler;

    @Autowired
    private CheckFindDynamicCommentAndReplyService checkFindDynamicCommentAndReplyService;

    @Autowired
    private VestRobotMessageService vestRobotMessageService;
    /**
     * 添加
     * @param findDynamicCommentDTO
     */
    @Transactional(rollbackFor = Exception.class)
    public FindDynamicCommentVO addFindDynamicCommentInfo(FindDynamicCommentDTO findDynamicCommentDTO) throws IOException {
        FindDynamicCommentVO findDynamicCommentVO = new FindDynamicCommentVO();
        FindDynamicVO findDynamicVO =findDynamicElasticsearch.getFindDynamicInfoByFindId(
                findDynamicCommentDTO.getFindId());

        if(findDynamicVO!=null){

            String target = NetEaseCloudUserService.getYunTextCheck(findDynamicCommentDTO.getComment());

            logger.info("发现动态评论反垃圾响应内容："+target+"，评论动态id："+findDynamicCommentDTO.getFindId()
                    +",评论内容："+findDynamicCommentDTO.getComment());

            JSONObject json = JSONObject.parseObject(target);

            int code = json.getIntValue("code");
            String msg = json.getString("msg");
            if(code == 200){
                JSONObject result = json.getJSONObject("result");
                int action = result.getIntValue("action");
                if(action==0){
                    int isWrite = 0;
                    if(findDynamicVO.getUserId().equals(findDynamicCommentDTO.getFromUserId())){
                        isWrite =1;
                    }
                    findDynamicCommentDTO.setIsWriter(isWrite);
                    DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    findDynamicCommentDTO.setCommentDate(df.format(LocalDate.now()));
                    DateTimeFormatter dfTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    findDynamicCommentDTO.setCommentTime(dfTime.format(LocalDateTime.now()));
                    findDynamicCommentDTO.setLikeNumber(0);
                    FindDynamicCommentInfo findDynamicCommentInfo = new FindDynamicCommentInfo();
                    BeanUtils.copyProperties(findDynamicCommentDTO,findDynamicCommentInfo);

                     int i = findDynamicCommentDao.addFindDynamicCommentInfo(findDynamicCommentInfo);
                    if(i>0){
                        //返回发布评论的所有字段
                        BeanUtils.copyProperties(findDynamicCommentInfo,findDynamicCommentVO);
                        UserCacheVo userCacheVo = userInfoCache.getUserCacheInfo(findDynamicCommentVO.getFromUserId());
                        findDynamicCommentVO.setNickName(userCacheVo.getNickName());
                        findDynamicCommentVO.setAge(userCacheVo.getAge());
                        findDynamicCommentVO.setVGrade(userCacheVo.getVGrade());
                        findDynamicCommentVO.setSex(userCacheVo.getSex());
                        findDynamicCommentVO.setIsVip(userCacheVo.getIsVip());
                        findDynamicCommentVO.setIsHost(userCacheVo.getIsHost());
                        findDynamicCommentVO.setVipLevel(userCacheVo.getVipLevel());
                        findDynamicCommentVO.setIcon(userCacheVo.getIcon());
                        findDynamicCommentVO.setStar(userCacheVo.getStar());
                        findDynamicCommentVO.setMGrade(userCacheVo.getMGrade());

                        findDynamicCommentVO.setIsSvip(userCacheVo.getIsSvip());
                        findDynamicCommentVO.setIsPlatinumVip(userCacheVo.getIsPlatinumVip());

                        findDynamicCommentVO.setEnergyGrade(userCacheVo.getUserLevel()
                                .getEnergyGrade());

                        String levelPic = userCacheVo.getUserLevel().getLevelPic();
                        String hostUserGradePic = userCacheVo.getHostUserLevel().getHostUserGradePic();
                        Integer hostLevel = userCacheVo.getHostUserLevel().getHostUserGrade();
                        findDynamicCommentVO.setLevelPic(levelPic==null ? "":levelPic);
                        findDynamicCommentVO.setHostUserGrade(hostLevel==null ? 0: hostLevel);
                        findDynamicCommentVO.setHostUserGradePic(hostUserGradePic==null ? "":hostUserGradePic);
                        DateTimeFormatter date = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                        String showTime = DateUtil.getShowTime(LocalDateTime.parse(findDynamicCommentVO.getCommentTime(), date));
                        findDynamicCommentVO.setShowTime(showTime);

                        integralRewardsAndPunishmentsHandler
                                .singleDynamicCommentAndReplyOver10People(findDynamicCommentInfo.getFindId(),
                                        findDynamicVO.getUserId(),findDynamicCommentVO.getFromUserId());

                        findDynamicCommentInfo.setIsSvip(userCacheVo.getIsSvip());
                        findDynamicCommentInfo.setIsPlatinumVip(userCacheVo.getIsPlatinumVip());

                        findDynamicCommentElasticsearch.addFindDynamicCommentInfo(findDynamicCommentInfo);

                        checkFindDynamicCommentAndReplyService.incrementDynamicCommentAndReplyNumber(findDynamicCommentDTO.getFromUserId());
                        if(findDynamicCommentVO.getIsWriter()==0){
                            sendSystemMessage(findDynamicVO);
                        }
                    }
                }else{
                    logger.info("发现动态评论发垃圾不通过，评论动态id："+findDynamicCommentDTO.getFindId()
                            +",评论内容："+findDynamicCommentDTO.getComment());
                    throw new ConsumeRuntimeException("4112","评论内容违规", HttpStatus.BAD_REQUEST);
                }
            }else{
                logger.error("发现动态评论反垃圾响应异常，状态码:"+code+"，状态描述："+msg+"评论动态id："+findDynamicCommentDTO.getFindId()
                        +",评论内容："+findDynamicCommentDTO.getComment());
            }
        }
        return findDynamicCommentVO;
    }

    /**
     * 发送自定义动态评论消息
     * @param findDynamicVO
     */
    private void sendSystemMessage(FindDynamicVO findDynamicVO) {
        String type = SpendSystemMessageType.FIND_DYNAMIC_COMMENT_TYPE.getCode();
        Map<String,Object> ext = new HashMap<>(1);
        ext.put("findId",findDynamicVO.getFindId());

        String template = SpendSystemMessage.FIND_DYNAMIC_COMMENT.getMessage();
        String[] colors = SpendSystemMessage.FIND_DYNAMIC_COMMENT.getColors();

        ext.put("template",template);

        List<String> templateList = new ArrayList<>(1);
        templateList.add(findDynamicVO.getFindTitle());

        ext.put("templateValue",templateList);
        ext.put("templateColors",colors);

        String message = SpendSystemMessage.FIND_DYNAMIC_COMMENT.getMessage(findDynamicVO.getFindTitle());

        vestRobotMessageService.getSendMsg(findDynamicVO.getUserId(),message,type,ext);
    }

    /**
     *
     * @param userId 请求用户id
     * @param findId
     * @param page
     * @param pageSize
     * @return
     * @throws IOException
     */
    public ResultFindDynamicCommentVO selectPage(long userId, int findId, Integer page, Integer pageSize) throws IOException {
        ResultFindDynamicCommentVO resultFindDynamicCommentVO = new ResultFindDynamicCommentVO();
        long total = findDynamicCommentElasticsearch.getCount(findId);
        resultFindDynamicCommentVO.setTotal(total);
        if(total==0){
            resultFindDynamicCommentVO.setResultList(new ArrayList<>());
        }else{
            List<FindDynamicCommentVO> list = findDynamicCommentElasticsearch.selectPage(findId,page,pageSize);

            for(FindDynamicCommentVO obj : list){
                ResultFindCommentReplyVO replyVO =findCommentReplyInfoService.selectPage(userId,obj.getId(),1,1);
                obj.setReplyChild(replyVO);
            }

            resultFindDynamicCommentVO.setResultList(list);


        }
        return resultFindDynamicCommentVO;
    }



}
